package com.fivium.bpd.component;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class QueryDefinition
    implements DocumentSerializable, Comparable<QueryDefinition>
{
  public static final String ELEMENT_QUERY_DEFINITION = "QUERY_DEFINITION";
  public static final String ELEMENT_QUERY_NAME       = "QUERY_NAME";
  public static final String ELEMENT_SQL              = "SQL";
  
  public static enum QUERY_TYPE {
    API, QUERY
  };
  
  private String queryName_;
  private String sql_;
  private QUERY_TYPE queryType_;
  
  public String getName()
  {
    return queryName_;
  }
  
  public void setName(String name)
  {
    queryName_ = name;
  }
  
  public String getSQL()
  {
    return sql_;
  }
  
  public void setSQL(String sql)
  {
    sql_ = sql;
    setType();
  }
  
  private void setType()
  {
    String startSqlLower = sql_.toLowerCase().trim();
    
    if (sql_ == null || sql_.equals("")) {
      queryType_ = null;
    } else if (startSqlLower.startsWith("begin") || startSqlLower.startsWith("declare")) {
      queryType_ = QUERY_TYPE.API;
    } else {
      queryType_ = QUERY_TYPE.QUERY;
    }
  }
  
  public QUERY_TYPE getType()
  {
    return queryType_;
  }

  @Override
  public Document serializeToDocument()
  {
    try {
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
      Document queryXml = documentBuilder.newDocument();
      
      Element rootElement = queryXml.createElement(ELEMENT_QUERY_DEFINITION);
      queryXml.appendChild(rootElement);
      
      Element queryNameElement = queryXml.createElement(ELEMENT_QUERY_NAME);
      queryNameElement.setTextContent(queryName_);
      rootElement.appendChild(queryNameElement);
      
      Element sqlElement = queryXml.createElement(ELEMENT_SQL);
      sqlElement.setTextContent(sql_);
      rootElement.appendChild(sqlElement);
      
      return queryXml;
    }
    catch (ParserConfigurationException e) {
      e.printStackTrace();
    }

    return null;
  }

  @Override
  public int compareTo(QueryDefinition qd)
  {
    return getName().compareTo(qd.getName());
  }
  
}
